package com.ruoyi.system.apiController;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.ZcUsers;
import com.ruoyi.system.properties.WechatConfigProperties;
import com.ruoyi.system.service.IZcOrdersService;
import com.ruoyi.system.service.IZcUsersService;
import com.ruoyi.system.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.security.KeyRep.Type.SECRET;

@RestController
public class LoginController extends BaseController {
    // 默认账户名前缀
    private static List<String> DEFAULT_NICKNAME_PREFIX = List.of("生活更美好", "大桔大利", "日富一日", "好柿开花", "柿柿如意", "一椰暴富", "大柚所为", "杨梅吐气", "天生荔枝");
    @Autowired
    private WechatConfigProperties wechatConfigProperties;
    @Autowired
    private IZcUsersService zcUsersService;

    private static final String JSCODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 获取微信code
     */
    @PostMapping("/api/wechat/login")
    public Map<String, Object> login(@RequestBody Map<String, String> request) {

        String code = request.get("code");
//
        try{
            Map<String, Object> response = new HashMap<>();
            response.put("appid",wechatConfigProperties.getAppId());
            response.put("secret",wechatConfigProperties.getSecret());
            response.put("js_code",code);
            response.put("grant_type","authorization_code");
            String result = HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session", response);
            System.out.println("result:" + result);
            JSONObject jsonObject = JSON.parseObject(result);
            String openid = jsonObject.getString("openid");
            String sessionKey = jsonObject.getString("session_key");

            // 从微信响应中获取 openid 和 session_key
            ZcUsers zcUsers = new ZcUsers();
            long time = new Date().getTime();
            //将long类型转换为String类型
            String timeStr = String.valueOf(time);
            System.out.println("timeStr:" + timeStr);
            zcUsers.setOpenId(openid);
            zcUsers.setSk(sessionKey);
            zcUsers.setAddTime(new Date());
            zcUsers.setNickname(DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size())) + timeStr.substring(timeStr.length()-4, timeStr.length()));
            zcUsers.setAvatarUrl("http://127.0.0.1:8080/profile/upload/2025/04/03/1702459332233-柯基_20250403163410A001.jpeg");
//            zcUsersService.insertZcUsers(zcUsers);
            //根据返回来的openid确认是否是新用户，如果是则保存，不是则更新
            LambdaQueryWrapper<ZcUsers> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ZcUsers::getOpenId, openid)
                    .eq(ZcUsers::getSk, sessionKey);
//            ZcUsers zcUsers1 = zcUsersService.getOne(wrapper);
            ZcUsers users = new ZcUsers();
            users.setOpenId(openid);
            users.setSk(sessionKey);
            List<ZcUsers> zcUsers1 =  zcUsersService.selectZcUsersList(users);
            Long id = 0L;
            String nickname = "";
            if (zcUsers1.size() == 0){
                zcUsersService.insertZcUsers(zcUsers);
                id = zcUsers.getUserId();
                nickname = zcUsers.getNickname();
            }else{
                zcUsers.setUserId(zcUsers1.get(0).getUserId());
                zcUsersService.updateZcUsers(zcUsers);
            }
            //生成token
            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            map.put("name", nickname);
            //使用JWT工具类，生成身份令牌
            String token = JwtUtils.generateJwt(map);
            Map<String, Object> objectHashMap = new HashMap<>();
            objectHashMap.put("token", token);
            objectHashMap.put("user", zcUsers);
            objectHashMap.put("success", true);

//            return AjaxResult.success(objectHashMap);
            return objectHashMap;
        }catch (Exception e){
            e.printStackTrace();
//            return AjaxResult.error("登录失败");
            return null;
        }

    }
}
